package com.rpay.common.factory;

import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;
import org.springframework.util.StringUtils;

import java.io.IOException;

/**
 * Title：
 * Description
 *
 * @author fxg06 on 2018/4/19
 * @version 1.0
 */
public class YamlPropertySourceFactory implements PropertySourceFactory {
    public YamlPropertySourceFactory() {
    }

    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        return name != null ? (new YamlPropertySourceLoader()).load(name, resource.getResource(), (String)null) : (new YamlPropertySourceLoader()).load(getNameForResource(resource.getResource()), resource.getResource(), (String)null);
    }

    private static String getNameForResource(Resource resource) {
        String name = resource.getDescription();
        if (!StringUtils.hasText(name)) {
            name = resource.getClass().getSimpleName() + "@" + System.identityHashCode(resource);
        }

        return name;
    }
}
